package com.share.device.sevice.impl;

import com.alibaba.fastjson.JSONObject;
import com.share.common.core.exception.ServiceException;
import com.share.device.sevice.IMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service
public class IMapServiceImpl implements IMapService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;


    @Override
    public JSONObject calculateLatLng(String address) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address={address}&key={key}";
        Map<String, String> map = new HashMap<>();
        map.put("address", address);
        map.put("key", key);

        JSONObject response = restTemplate.getForObject(url, JSONObject.class, map);
        if (response.getIntValue("status") != 0) {
            throw new ServiceException("地图解析异常");
        }

        JSONObject result = response.getJSONObject("result");
        System.out.println(result.toJSONString());
        return result.getJSONObject("location");
    }

    /**
     * 计算到门店的距离方法
     * @param startLongitude
     * @param startLatitude
     * @param endLongitude
     * @param endLatitude
     * @return
     */
    @Override
    public Double calculateDistance(String startLongitude, String startLatitude, String endLongitude, String endLatitude) {
        String url = "https://apis.map.qq.com/ws/direction/v1/walking/?from={from}&to={to}&key={key}";

        HashMap<String, String> map = new HashMap<>();
        map.put("from", startLatitude + "," + startLongitude);
        map.put("to", endLatitude + "," + endLongitude);
        map.put("key", key);

        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        if (result.getIntValue("status") != 0) {
            throw new ServiceException("地图服务调用失败");
        }

        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        return route.getBigDecimal("distance").doubleValue();
    }
}
